import { DatePicker, Segmented } from 'antd';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';

const defaultOptions = [
  {
    label: '全部',
    value: 0,
  },
  {
    label: '近1个月',
    value: 30,
  },
  {
    label: '近3个月',
    value: 90,
  },
  {
    label: '近半年',
    value: 180,
  },
  {
    label: '近一年',
    value: 365,
  },
  {
    label: '自定义',
    value: -1,
  },
];

type EventValue<DateType> = DateType | null;
type RangeValue<DateType> = [EventValue<DateType>, EventValue<DateType>] | null;

interface TimePiceChoiceProps {
  options?: { label: string; value: number }[];
  defaultRange?: RangeValue<dayjs.Dayjs>;
  value?: number;
  onChange?(value: number, range?: TimePiceChoiceProps['defaultRange']): void;
}

export default function TimePiceChoice({ options, defaultRange, value, onChange }: TimePiceChoiceProps) {
  const _options = useMemo(() => {
    return options ?? defaultOptions;
  }, [options]);

  const [_range, setRange] = useState(defaultRange);

  return (
    <div>
      <Segmented
        value={value}
        options={_options}
        onChange={(value) => {
          if (typeof value === 'number') {
            let range: TimePiceChoiceProps['defaultRange'];
            if (value > 0) {
              range = [dayjs().subtract(value, 'days'), dayjs()];
            } else if (value === 0) {
              range = [null, null];
            } else if (value === -1) {
              range = _range;
            }
            onChange?.(value, range);
          }
        }}
      />
      <DatePicker.RangePicker
        value={_range}
        style={{
          marginLeft: '16px',
          display: value !== -1 ? 'none' : undefined,
        }}
        onChange={(a) => {
          setRange(a as RangeValue<dayjs.Dayjs>);
          onChange?.(-1, a as RangeValue<dayjs.Dayjs>);
        }}
      />
    </div>
  );
}
